package com.flyee.io.webservice{
	
	import com.flyee.communicate.Communicate;
	import com.flyee.events.AuthenticationFailureEvent;
	import com.flyee.events.RemoteExceptionEvent;
	import com.flyee.io.Config;
	import com.flyee.utils.MyLog;
	
	import flash.events.EventDispatcher;
	
	import mx.core.Application;
	import mx.messaging.ChannelSet;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	/**
	 * Super class for all remote services that contains some generic methods.
	 */
	public class RemoteService extends EventDispatcher
	{
		protected var DEFAULT_TIMEOUT:int=200;
		private static var BAD_CREDENTIALS:String="org.springframework.security.BadCredentialsException : Bad credentials";
		
		private static var instance : RemoteService;
		
		/**
		 * 取得该类的单例 
		 */
		public static function getInstance() : RemoteService {
		 	if(instance==null)
		 		instance = new RemoteService(new Singleton());
		 	return instance;
		}
		
		public function RemoteService(s : Singleton){			
		}
		
		/**
		 * 工厂模式 生产一个远程BEAN 
		 */
		public function getRemoteBean(destination:String, comm : Communicate) : RemoteBean {
			var remoteObject : RemoteBean = new RemoteBean(destination, comm);
			remoteObject.channelSet = Config.getInstance().amfChannelSet;
			remoteObject.requestTimeout=DEFAULT_TIMEOUT;
			remoteObject.showBusyCursor=true;
			remoteObject.addEventListener(FaultEvent.FAULT, onRemoteException);
			remoteObject.addEventListener(ResultEvent.RESULT, responseHandle);
			return remoteObject;
		}
		
		public function get amfChannelSet():ChannelSet
		{
			return Config.getInstance().amfChannelSet;
		}

		/**
		 * 远程方法调用返回值的事件处理
		 */
		protected function responseHandle(event : ResultEvent) : void {
			//调用远程BEAN中注册的回调方法处理结果
			event.target.communicate.response(event.result);
			//暂定，数据处理完成后调用释放方法
			dispose();
		}

		/**释放*/
		private function dispose() : void {
			//....etc
		}

		protected function onRemoteException(event:FaultEvent) : void
		{
			event.target.removeEventListener(FaultEvent.FAULT, onRemoteException);
			MyLog.error('code : ' + event.fault.faultCode + ', message : ' + event.fault.faultString + ',detail : ' + event.fault.faultDetail);

			if (event.fault.faultString == BAD_CREDENTIALS)
			{
				Application.application.dispatchEvent(new AuthenticationFailureEvent(AuthenticationFailureEvent.AUTHENTICATION_FAILURE, "problem while authenticating"))
			}
			else
			{
				Application.application.dispatchEvent(new RemoteExceptionEvent(RemoteExceptionEvent.REMOTE_EXCEPTION, "unknown problem occurred during a remote call : " + event.fault.message));
			}
//			event.target = null;
		}
	}
}
class Singleton{}